package cn.tom.controller.adm;

import cn.tom.tools.XResp;
import cn.tom.entity.Book;
import cn.tom.tools.XJson;
import cn.tom.service.BookService;
import cn.tom.service.LargeFileService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@RestController
@Slf4j
@RequestMapping("/api/adm/book")
public class AdmBookController  {
    @Resource
    private BookService bookService;
    @Resource
    private LargeFileService largeFileService;

    @GetMapping("/findByBookid/{id}")
    public XJson findOne(@PathVariable Integer id){
        Book one = bookService.findOne(id);
        return XResp.pack(200,"",one);
    }

    @GetMapping("/findTopSale/{num}")
    public XJson findTopSale(@PathVariable Integer num){
        if(num == null)num = 5;
        if(num < 1)num = 1;
        if(num > 20)num = 20;
        List<Book> list = bookService.findTopSale(num);
        return XResp.pack(200,"",list);
    }

    @GetMapping("/findByPage/{start}/{num}")
    public XJson findBookPages(@PathVariable("start")Integer start
                                , @PathVariable("num")Integer num){
        if ( start == null || start<1 ) start = 1;
        List<Book> list = bookService.findBookPages(start, num);
        int total = bookService.countALL();
        Map<String,Object> map = new HashMap<>();
        map.put("books",list);
        map.put("total",total);
        return XResp.pack(200,"",map);
    }

    /**
     * 商品添加 或 修改
     *  通过注解@RequestParam去指定key获取value 绑定 MultipartFile
     *
     * 1.ID 大于 0 修改：
     *              1.前端有上传文件：先删除原来的图片，
     *              然后使用原来的图片ID进行添加，没有就跳过
     *              2.修改商品
     *              3.查找商品，然后响应给前端
     * 2.ID 小于或等于 0 添加：
     *              1.生成一个新的UUID，并去掉 ：短横杠
     *              2.前端有上传文件：UUID做图片编号并添加，没有跳过
     *              3.将UUID设置进商品的图片编号
     *              4.添加后查找商品，并响应给前端
     * @param file
     * @param book
     * @return
     * @throws IOException
     */
    @PostMapping("/addUp")
    public XJson addUpBook(
            @RequestParam(value = "mypic" , required = false)MultipartFile file
            , Book book)throws IOException {
        if(book.getId() > 0){
            if(file != null && file.getSize() > 0){
                largeFileService.delete(book.getPic());
                byte[] bytes = file.getBytes();
                String fileName = file.getOriginalFilename();
                largeFileService.add(book.getPic(),fileName,bytes);
            }
            int n = bookService.update(book);
            if(n == 0)return XResp.pack(501,"修改失败","");
            Book one = bookService.findOne(book.getId());
            Map<String,Object> map = new HashMap<>();
            map.put("book",one);
            return XResp.pack(200,"修改成功",map);
        }
        //添加
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-","");
        if(file != null && file.getSize() > 0){
            byte[] bytes = file.getBytes();
            String fileName = file.getOriginalFilename();
            largeFileService.add(uuid,fileName,bytes);
        }
        book.setPic(uuid);
        int n =  bookService.add(book);
        if(n == 0)return XResp.pack(501,"添加失败","");
        Book one = bookService.findOne(book.getId());
        Map<String,Object> map = new HashMap<>();
        map.put("book",one);
        return XResp.pack(200,"添加成功",map);
    }
    //删除后返回原来那一页
    @GetMapping("/del/{id}/{start}/{num}")
    public XJson del(@PathVariable("id")   Integer id
                    ,@PathVariable("start")Integer start
                   , @PathVariable("num")  Integer num){
        bookService.del(id);
        Object data = findBookPages(start, num).getData();
        return XResp.pack(200,"删除成功",data);
    }
}
